package org.ocean.online.web.workspace.tool;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.HiddenField;
import org.apache.wicket.model.Model;
import org.ocean.online.sys.DbGuard;
import org.ocean.online.utils.ParamUtil;
import org.ocean.online.wicket.NeedLoginPage;
import org.ocean.online.wicket.SimpleAjaxSubmitLink;
import org.springframework.jdbc.UncategorizedSQLException;

public class EditModelData extends NeedLoginPage{

	private static final long serialVersionUID = -132080701796573907L;
	HiddenField<String> modelName = new HiddenField<String>("modelName",new Model<String>(""));
	HiddenField<String> jsonStr = new HiddenField<String>("jsonData",new Model<String>(""));
	JSONObject jsonObject = new JSONObject();
	public EditModelData(){
		this.modelName.setDefaultModelObject(this.getStringParam("modelName"));
		query();
		jsonStr.setOutputMarkupId(true);
		final Form<?> form = new Form("form",new Model());
		add(form);
		form.add(jsonStr);
		form.setOutputMarkupId(true);
		SimpleAjaxSubmitLink saveData = new SimpleAjaxSubmitLink("saveData") {

			@Override
			protected void onSubmit(AjaxRequestTarget target) {
				jsonObject= JSONObject.fromObject(getStringParam("jsonData"));
				JSONObject jobj = jsonObject.getJSONObject("changeData");
				try{
					if(StringUtils.isEmpty(jobj.getString("uid"))){
						String uid = insertData(jobj);
						target.appendJavaScript("updateUID('"+uid+"')");
					}else{
						updateData(jobj);
					}
				}catch(UncategorizedSQLException ex){
					target.appendJavaScript("alert('save data faield "+ex.getSQLException().getMessage()
							+" are you sure you are editing data in "+modelName.getDefaultModelObjectAsString()
							+" and columns are right,do not use alias when you want to edit data')");
				}
				catch(Exception ex){
					ex.printStackTrace();
					target.appendJavaScript("alert('save data faield')");
				}
			}
			
		};
		form.add(saveData);
		form.add(modelName);
		
		SimpleAjaxSubmitLink delData = new SimpleAjaxSubmitLink("delData") {

			@Override
			protected void onSubmit(AjaxRequestTarget target) {
				jsonObject= JSONObject.fromObject(getStringParam("jsonData"));
				try{
					deleteData(jsonObject.getJSONObject("changeData"));
				}catch(Exception ex){
					target.appendJavaScript("alert('delete data faield')");
				}
			}
			
		};
		form.add(delData);
		
		SimpleAjaxSubmitLink queryBySql = new SimpleAjaxSubmitLink("queryBySql") {

			@Override
			protected void onSubmit(AjaxRequestTarget target) {
				try{
					jsonObject= JSONObject.fromObject(getStringParam("jsonData"));
					query();
					target.add(jsonStr);
					target.appendJavaScript("loadData()");
				}catch(UncategorizedSQLException ex){
					ex.printStackTrace();
					target.appendJavaScript("alert('query faield "+ex.getSQLException().getMessage()+"')");
				}catch(Exception ex){
					target.appendJavaScript("alert('query faield')");
				}
			}
			
		};
		form.add(queryBySql);
	}
	private String insertData(JSONObject jobj){
		jobj.put("uid", UUID.randomUUID().toString());
		this.getDb().insert(this.modelName.getDefaultModelObjectAsString(), ParamUtil.toMap(jobj));
		return jobj.getString("uid");
	}
	private void updateData(JSONObject jobj){
		Map cond = new HashMap();
		cond.put("uid", jobj.get("uid"));
		this.getDb().update(modelName.getDefaultModelObjectAsString(), ParamUtil.toMap(jobj), cond);
	}
	
	private void deleteData(JSONObject jobj){
		String delete = "delete from ? where uid=?";
		this.getDb().execute(delete, modelName.getDefaultModelObjectAsString(),jobj.get("uid"));
	}
	
	private void query(){
		DbGuard db = this.getDb();
		String sql="";
		if(jsonObject.containsKey("querySql")){
			 sql = jsonObject.getString("querySql");
		}
		
		if(StringUtils.isEmpty(sql)){
			sql = "select * from "+modelName.getDefaultModelObjectAsString();
		}
		List<Map> result = (List<Map>) db.queryForPage(sql, 3, 1).get("rows");
		JSONObject tableData = new JSONObject();
		tableData.put("rows", result);
		
		String[] list = db.getColumns(sql);
		JSONArray colsData= new JSONArray();
		for(String column : list){
			JSONObject obj = new JSONObject();
			obj.put("field", column);
			obj.put("title", column);
			obj.put("editor", "text");
			if(!"uid".equals(column)){
				obj.put("readonly", "true");
			}
			colsData.add(obj);
		}
		
		this.jsonObject.put("tableData", tableData);
		this.jsonObject.put("columns", colsData.toString());
		this.jsonStr.setDefaultModelObject(this.jsonObject.toString());
	}
}
